<?php


namespace app\bock\type\action;


use app\bock\type\bock\IBock;
use app\bock\type\INode;
use app\bock\type\NodeStack;
use app\bock\type\Point;
use app\bock\type\stack\PanelStack;

class CollisionCheck
{
    /**
     * @var PanelStack
     */
    protected $panelStack;

    /**
     * @var IBock
     */
    protected $bock;


    public function __construct($panelStack, $bock)
    {
        $this->panelStack = $panelStack;

        $this->bock = $bock;
    }

    /**
     * 检查该堆和当前图形是否有碰撞, 即该块下一个位置是否为堆
     * 检查改块是不是到底了, 即 row = height - 1, 如果是也代表碰撞
     */
    public function check()
    {
        $nodes = $this->bock->getAllEffNode();

        foreach ($nodes as $item)
        {
            /**
             * @var INode $item
             */
            $checkPoint = $item->getPoint()->addPoint(new Point(1,0));
            if($this->panelStack->isStack($checkPoint) || $checkPoint->getRow() === ($this->panelStack->getHeight()))
            {
                return true;
            }
        }

        return false;
    }

    public function isOver()
    {
        // 判断第一行是否有堆
        foreach ($this->panelStack->getOneRowNodes() as $item)
        {
            if ($item instanceof NodeStack)
            {
                throw new \Exception('GAME OVER!');
            }
        }
    }

    /**
     * 判断旋转过后的图形是否碰到了stack
     * @return IBock|bool
     */
    public function isCanRotate()
    {
        $bock = $this->bock->rotate();

        $nodes = $bock->getAllEffNode();

        foreach ($nodes as $node)
        {
            /**
             * @var INode $node
             */
            if($this->panelStack->isStack($node->getPoint()))
            {
                return false;
            }
        }


        return $bock;
    }
}